<?php

namespace App\Http\Controllers\Admin\Login;

use DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Admin\Login\Api\loginApi;
use App\Model\AdminUsers;
use App\Http\Controllers\Common\CommonCodeApi;

class loginControllers extends Controller
{
    public function index()
    {
        return view('Admin/Login/index');
    }

    public function json($code, $msg, $data = [])
    {
        return response()->json([
        'status' => $code,
        'msg' => $msg,
        'data' => $data,
        ]);
    }

    public function dologin(Request $request){

        // dd($request->all());
        $codemod = new CommonCodeApi();

        $dd = $codemod->CheckCode($request);

        if (!$dd) {
            return $this->json(702, '验证码错误');
        }
        

        $user = $request->all()['uname'];
        $pass = $request->all()['pass'];

        //有这个账号----------------------------------这个账号是否可用
        $usermod = AdminUsers::where('uname', $user)->where('state', 0);

        if(!$usermod->first()){
            return $this->json(703, '没有这个账号');
        }

        $userarr = $usermod->first()->toArray();
        //63ee451939ed580ef3c4b6f0109d1fd0
        //63ee451939ed580ef3c4b6f0109d1fd0

        //判断密码是否正确
        if ($userarr['pass'] !== md5(md5($pass))) {
            return $this->json(703, '密码错误');
        }else{
            $request->session()->put('admin_user', $user);
            $request->session()->put('admin_user_arr', $userarr);

            //将登录用户的权限传进session
            $adminmod = new AdminUsers();
            $permission = $adminmod->haspermission($userarr['id']);
            $request->session()->put('admin_user_permission', $permission);

            return $this->json(200, '登录成功');
        }


    }

    public function loginout(Request $request)
    {
        $request->session()->forget('admin_user');
        $request->session()->forget('admin_user_arr');
        $request->session()->forget('admin_user_permission');

        return redirect('/Admin');
    }
}
